#!/usr/bin/python
#coding=utf-8
import psutil
import json
import threading
import os
import subprocess

file_config = 'monitor.conf'

class ProcessConf:
    __conf_dict = dict()
    def load(self,confs=[]):
        for item in confs:
            conf_item = ProcessConfItem(item['name'])
            if None != item.get('timeout'):
                conf_item.set_timout(item.get('timeout'))
            if None != item.get('path'):
                conf_item.set_path(item.get('path'))
            if None != item.get('cmd'):
                conf_item.set_cmd(item.get('cmd'))   

            self.__conf_dict[conf_item.name] = conf_item

    def conf_item(self,name):
        return self.__conf_dict.get(name)
    
    def conf_dict(self):
        return self.__conf_dict
        

class ProcessConfItem:
    def __init__(self,name):
        self.name = name
        self.timeout = 0
        self.path = "."
        self.cmd = ""
    
    def set_path(self,path):
        self.path = path
        
    def set_timout(self,timeout):
        self.timeout = timeout
    
    def set_cmd(self,cmd):
        self.cmd = cmd

    def __repr__(self):
        return repr((self.name,self.timeout,self.path))



def get_process(conf):
    proc_list = dict()
    for proc in psutil.process_iter():
        try:
            proc_item = proc.as_dict(attrs=['name','pid'])
        except psutil.NoSuchProcess:
            pass
        else:
            proc_list[proc_item['name']] = proc_item['pid']
    

    conf_dict = conf.conf_dict()
    for item in conf_dict.values():
        if None == proc_list.get(item.name):
            # 进程中没有找到，需要重启
            run_process(item)



def run_process(process_conf):
    os.chdir(process_conf.path)
    print(os.getcwd())
    if "" == process_conf.cmd:
        res = subprocess.call('nohup ./'+process_conf.name+ ' &',shell=True)
        print("执行结果返回值%d " % (res))
    else:
        res = subprocess.call(process_conf.cmd,shell=True)
        print("执行结果返回值%d " % (res))
    

def load_jscon_conf():
    conf = ProcessConf()
    with open(file_config,'r') as fconf:
        conflist = json.loads(fconf.read())
        conf.load(conflist)
    return conf


conf = load_jscon_conf()
def timer_to_scan_process():
    get_process(conf)
    global timer
    timer = threading.Timer(1,timer_to_scan_process)
    timer.start()

timer = threading.Timer(5,timer_to_scan_process)
timer.start()
